#import "SEGQueryauthinfoManager.h"

#define kNSUserDefaultsEnterpriseId @"seg_EnterpriseId"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif
#if __has_include(<Commom/SEGHTTPBusinessManager.h>)
#import <Commom/SEGHTTPBusinessManager.h>
#else
#import "SEGHTTPBusinessManager.h"
#endif

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

static id _QueryAuthInfoManager;
static dispatch_once_t onceToken;

@implementation SEGQueryauthinfoManager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _QueryAuthInfoManager = [[self alloc] init];
    });
    return _QueryAuthInfoManager;
}

+(void)destroyResource{
    onceToken = 0;
    _QueryAuthInfoManager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----
-(void)requestQueryauthinfoWithCommunityid:(NSString*)communityId finished:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))finished{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:communityId forKey:@"communityId"];
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/enterprise-app/user/queryAuthInfo.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed) {
            finished(isSuccessed,nil,codeType,error.localizedDescription);
            return;
        }
        
        self.QueryAuthInfo = [SEGQueryauthinfoModel yy_modelWithDictionary:result];
        if (self.QueryAuthInfo.data && self.QueryAuthInfo.data.userInfo && self.QueryAuthInfo.data.userInfo.enterpriseUserId && self.QueryAuthInfo.data.userInfo.enterpriseUserId.length > 0) {
            [[NSUserDefaults standardUserDefaults] setObject:self.QueryAuthInfo.data.userInfo.enterpriseUserId forKey:kNSUserDefaultsEnterpriseId];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [SEGQueryauthinfoManager seg_SaveSEGQueryauthinfoModelWithEnterpriseUserId:self.QueryAuthInfo];
        }
        finished(isSuccessed,result,codeType,error.localizedDescription);
        return;
    }];
}

/**
 * 保存本地缓存的用户信息
 * @author Sam
 * @param userAccount  服务器下发的缓存信息
 * @return YES：本地缓存成功，NO：本地缓存失败
 */
+ (BOOL)seg_SaveSEGQueryauthinfoModelWithEnterpriseUserId:(SEGQueryauthinfoModel*)userAccount
{
    NSString* path = [self path_UserInforWithEnterpriseUserId:userAccount.data.userInfo.enterpriseUserId];
    return [NSKeyedArchiver archiveRootObject:userAccount toFile:path];
}

/**
 * 获取本地缓存的用户信息
 * @author Sam
 * @return 本地缓存的用户信息模型
 */
+ (SEGQueryauthinfoModel *)seg_GetSystemAccount;
{
    NSString * userID = [self segEnterpriseIdFromLocal];
    NSString* path = [self path_UserInforWithEnterpriseUserId:userID];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [[SEGQueryauthinfoModel alloc]init];
    }
    // TODO: 组件化，在覆盖旧APP的时候会闪退，第一次覆盖，需要进行定位！
    SEGQueryauthinfoModel* account = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return account;
}

/**
 * 获取本地的用户ID
 * @author Sam
 */
+(NSString*)segEnterpriseIdFromLocal{
    return ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:kNSUserDefaultsEnterpriseId]);
}

/**
 * 用户信息本地缓存路径
 * @author Sam
 */
+ (NSString*)path_UserInforWithEnterpriseUserId:(NSString*)enterpriseUserId
{
    return [NSString stringWithFormat:@"%@/EnterpriseUserId_%@.data", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject, enterpriseUserId];
}
#pragma mark - HTTP----END----

#pragma mark - GETTER----BEGIN----
-(SEGQueryauthinfoModel *)QueryAuthInfo{
    if (!_QueryAuthInfo) {
        _QueryAuthInfo = [[SEGQueryauthinfoModel alloc]init];
        _QueryAuthInfo = [SEGQueryauthinfoManager seg_GetSystemAccount];
    }
    return _QueryAuthInfo;
}
#pragma mark - GETTER----END----
@end

